﻿using System;
using System.Collections.Generic;
using System.Web.ModelBinding;
using RMS.Models;
using RMS.Models.Repository;
using RMS.Pages.Helpers;
using System.Net.Mail;
using System.Net;

namespace RMS.Pages {
    public partial class Checkout : System.Web.UI.Page {
        protected string result = "";
        protected decimal resultTotal = 0;
        protected string resultEmail = "";
        public string currentRetreatDate = "";
        
        protected void Page_Load(object sender, EventArgs e) {

            checkoutForm.Visible = true;
            checkoutMessage.Visible = false;
                       
                                                                     
            if (IsPostBack) {
                               
                Reservation myOrder = new Reservation();
                if (TryUpdateModel(myOrder,
                   new FormValueProvider(ModelBindingExecutionContext))) {

                    myOrder.OrderLines = new List<OrderLine>();

                    Cart myCart = SessionHelper.GetCart(Session);

                    foreach (CartLine line in myCart.Lines) 
                    {
                        myOrder.Res_RetID = line.Retreat.Ret_ID;

                        myOrder.OrderLines.Add(new OrderLine 
                        {
                            Reservation = myOrder,
                            Retreat = line.Retreat,
                            Quantity = line.Quantity,
                        });
                    }

                    if (Session["ID"] != null)
                    {
                        myOrder.Res_UsID = (int)Session["ID"];
                       
                    }

                    new Repository().SaveReservation(myOrder);
                    
                    checkoutForm.Visible = false;
                    checkoutMessage.Visible = true;
                    
                    // Create Registration Result String
                    foreach (CartLine line in myCart.Lines)
                    {
                        result += line.Retreat.Ret_Title;
                    }
                    resultEmail = myOrder.Res_Email;
                    resultTotal = CartTotal;

                    // Clears Cart 
                    myCart.Clear();
                    
                    // Refreshes page on item removal to avoid PostBack issues
                    //Response.Redirect(Request.RawUrl);
                }
           
               
            }

        }

        // Methods to populate retreat date combobox
        public void setCurrentRetreatDate(string input)
        {
            currentRetreatDate = input;
        }

        public string getCurrentRetreatDate()
        {
       
           return currentRetreatDate;
          
        }

        // Formats dates for chosen date combobox (utilizes | as delimeter)
        public string dateFormat(string input)
        {
            string str = input;
            Boolean notValid = true;
            int num;
            int count = 0;
            string temp = "";
            

            while (notValid)
            {

                num = str.IndexOf('|', 0);

                if (num == -1)
                {
                    if (count == 0)
                    {
                        temp = "<option value=\"" + str + "\">" + str + "</option>";
                    }
                    else
                    {
                        temp += "<option value=\"" + str + "\">" + str + "</option>";
                    }

                    notValid = false;
                }
                else
                {
                    temp += "<option value=\"" + str.Substring(0, num) + "\">" + str.Substring(0, num) + "</option>";
                    str = str.Substring(num + 1);
                }

                count++;
            }
            
            return temp;
        }


        public decimal GetResultTotal
        {
            get
            {
                return resultTotal;
            }
        }

        public string GetResultString
        {
            get
            {
                return result;
            }
        }

        public IEnumerable<CartLine> GetCartLines()
        {
            return SessionHelper.GetCart(Session).Lines;
        }

        public decimal CartTotal
        {
            get
            {
                return SessionHelper.GetCart(Session).ComputeTotalValue();
            }
        }

        public int CountCartLines()
        {
            int count = 0;

            foreach (CartLine i in GetCartLines())
            {
                count++;
            }

            return count;
        }

        protected string GenerateEmail()
        {
            string response = " ";

            try
            {
                MailMessage mailMessage = new MailMessage();

                // Custom Strings
                string email = resultEmail;
                string body = "Greetings,\n\n" + "You have sucessfully registered for a retreat at the Redemptorist Retreat Center." +
                               "\n\n The Retreat Registered for: " + result + "\n\n Reservation Total: $ " + resultTotal +
                               "\n\n We look forward to seeing you! \n\n The Redemptorist Reteat Center";

                mailMessage.To.Add(email);
                mailMessage.To.Add("rrc.maintenance@gmail.com");

                mailMessage.From = new MailAddress("rrc.maintenance@gmail.com");
                mailMessage.Subject = "Thank You for registering for a retreat at the Redemptorist Retreat Center!";
                mailMessage.Body = body;
                SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.Port = 587;
                smtpClient.Credentials = new NetworkCredential("rrc.maintenance", "rrctest12345");
                smtpClient.EnableSsl = true;
                smtpClient.Send(mailMessage);

                response = "Confirmation e-mail sent to: " + email;
                Response.Write(response);

            }
            catch (Exception ex)
            {

                response = "Error: Could not sent e-mail... " + ex.Message;
                Response.Write(response);
            }

            return response;
        }

    }

    
}
